package com.example.sensors;

import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

import com.example.singletones.contextObj;

public class Sensor_Power extends AbstractSensor {
	public static final String NAME = "POWER";
	private Sensor_Power_Helper mSensor_Power_Helper = new Sensor_Power_Helper();

	private class Sensor_Power_Helper extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Sensor_Power.this.onReceive(context, intent);
		}
	}

	public Sensor_Power() {
		enableSensor();
	}

	public void disableSensor() {
		super.disableSensor();
		contextObj.getInstance().getmContext()
				.unregisterReceiver(mSensor_Power_Helper);
	}

	public void enableSensor() {
		super.enableSensor();
		contextObj
				.getInstance()
				.getmContext()
				.registerReceiver(mSensor_Power_Helper,
						new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	}

	private String getPlugTypeString(int plugged) {
		String plugType = "Unknown";

		switch (plugged) {
		case BatteryManager.BATTERY_PLUGGED_AC:
			plugType = "AC";
			break;
		case BatteryManager.BATTERY_PLUGGED_USB:
			plugType = "USB";
			break;
		}

		return plugType;
	}

	private String getStatusString(int status) {
		String statusString = "Unknown";

		switch (status) {
		case BatteryManager.BATTERY_STATUS_CHARGING:
			statusString = "Charging";
			break;
		case BatteryManager.BATTERY_STATUS_DISCHARGING:
			statusString = "Discharging";
			break;
		case BatteryManager.BATTERY_STATUS_FULL:
			statusString = "Full";
			break;
		case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
			statusString = "Discharging";
			break;
		}

		return statusString;
	}

	public void onReceive(Context arg0, Intent intent) {
		int status = intent.getIntExtra("status", 0);
		int plugged = intent.getIntExtra("plugged", -1);

		Map<String, Object> eventArgs = initEventArgs();
		eventArgs.put("eventType", "sensorInfoReceived");
		eventArgs.put("status", getStatusString(status));
		eventArgs.put("plugType", getPlugTypeString(plugged));
		OnSensorChanged(eventArgs);
	}

	public String getSensorName() {
		return NAME;
	}
}
